﻿using Adalbertus.BudgetPlanner.Domain;
using NHibernate;

namespace Adalbertus.BudgetPlanner.Infrastructure
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly ISession _session;
        private readonly ITransaction _transaction;

        public ISession Session
        {
            get { return _session; }
        }

        public UnitOfWork(ISession session)
        {
            this._session = session;

            session.FlushMode = FlushMode.Commit;
            _transaction = session.BeginTransaction();
        }

        public void Commit()
        {
            _transaction.Commit();
        }

        public void Dispose()
        {
            Dispose(true);
            System.GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!_transaction.WasCommitted)
                {
                    _transaction.Rollback();
                }

                _session.Close();
            }
        }
    }
}
